package botcraft.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Worker implements Runnable {
	private static final Logger logger = Logger.getLogger(Worker.class.getName());
	
	private final Socket socket;
	private final BlockingQueue<String> inputQueue;
	private final BlockingQueue<String> outputQueue;
	private final BufferedReader input;
	private final PrintWriter output;
	
	public Worker(final Socket socket, final BlockingQueue<String> inputQueue, final BlockingQueue<String> outputQueue, final URL gameUrl) throws IOException {
		this.socket = socket;
		this.inputQueue = inputQueue;
		this.outputQueue = outputQueue;
		input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		output = new PrintWriter(socket.getOutputStream());
		logger.info("Accepted connection from " + this);
		output.println(gameUrl);
		output.flush();
	}
	
	@Override
	public void run() {
		final Thread sender = new Thread(new Sender(this, outputQueue, output));
		final Thread receiver = new Thread(new Receiver(this, inputQueue, input));
		sender.start();
		receiver.start();
		try {
			sender.join();
			receiver.join();
		} catch (InterruptedException e) {
			return;
		} finally {
			try {
				socket.shutdownInput();
				socket.shutdownOutput();
				socket.close();
				logger.info("Closed connection to " + this);
			} catch (IOException e) {
				logger.log(Level.WARNING, "Error closing connection to " + this, e);
			}
		}
	}
	
	@Override
	public String toString() {
		return socket.getInetAddress().toString();
	}
}
